package ar.edu.unlam.tpfinal.struts.actions;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import ar.edu.unlam.tpfinal.result.ProcessResult;
import ar.edu.unlam.tpfinal.service.TransactionService;
import ar.edu.unlam.tpfinal.service.TransactionTypeService;
import ar.edu.unlam.tpfinal.service.exceptions.ServiceException;
import ar.edu.unlam.tpfinal.struts.forms.TransactionForm;

public class TransactionSaveAction extends Action {
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
								 HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		TransactionForm transactionForm = (TransactionForm)form;
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
		TransactionService ts = (TransactionService) context.getBean("transactionService");
		ProcessResult processResult = validate(transactionForm);
		if(!processResult.isError()){
			processResult = ts.saveTransaction(transactionForm);
		}
		if(processResult.isError()){
			transactionForm.setErrors(processResult.getProcessError());
			request.setAttribute("transactionForm", transactionForm);
			List<LabelValueBean> priorityComboBox;
			List<LabelValueBean> clientListMultibox;
			List<LabelValueBean> transactionTypeComboBox;
			List<LabelValueBean> statusComboBox;
			
			clientListMultibox = ts.getAllClients();
			if(clientListMultibox==null){
				clientListMultibox = new ArrayList<LabelValueBean>();
			}
			
			priorityComboBox = ts.getAllPriorities();
			if(priorityComboBox==null){
				priorityComboBox = new ArrayList<LabelValueBean>();
			}
			
			transactionTypeComboBox = ts.getAllTransactionTypes();
			
			statusComboBox = ts.getAllStatus();
			
			request.setAttribute("statusComboBox", statusComboBox);
			request.setAttribute("transactionTypeComboBox", transactionTypeComboBox);
			request.setAttribute("priorityComboBox", priorityComboBox);
			request.setAttribute("clientListMultibox", clientListMultibox);
			request.setAttribute("errors", processResult.getProcessError());
			return mapping.findForward("failure");
		}
		
		List<TransactionForm> transactionFormList = ts.listTransaction();
		
		request.setAttribute("transactionList", transactionFormList);
		if(processResult.isError()){
			request.setAttribute("errors", processResult.getProcessError());	
		} else {
			request.setAttribute("errors", "");
		}
		
		return mapping.findForward("success");
	}

	private ProcessResult validate(TransactionForm transactionForm) {
		ProcessResult processResult = new ProcessResult(); 
		if(transactionForm.getFromDate() == null || transactionForm.getFromDate().equals("")){
			processResult.addProcessError("Fecha desde obligatoria", new ServiceException("Fecha desde obligatoria"));
			return processResult;
		}
		if(transactionForm.getFromDate() != null){
			SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
			try {
				sdf.parse(transactionForm.getFromDate());
			} catch (ParseException e) {
				processResult.addProcessError("Formato de fecha dd-MM-yyyy", new ServiceException("Formato de fecha dd-MM-yyyy"));
				return processResult;
			}
		}
		if(transactionForm.getToDate() == null || transactionForm.getToDate().equals("")){
			processResult.addProcessError("Fecha hasta obligatoria", new ServiceException("Fecha hasta obligatoria"));
			return processResult;
		}
		if(transactionForm.getToDate() != null){
			SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
			try {
				sdf.parse(transactionForm.getFromDate());
			} catch (ParseException e) {
				processResult.addProcessError("Formato de fecha dd-MM-yyyy", new ServiceException("Formato de fecha dd-MM-yyyy"));
				return processResult;
			}
		}
		if(transactionForm.getSelectedItems() == null || transactionForm.getSelectedItems().length<=0){
			processResult.addProcessError("Seleccione por lo menos 1 cliente", new ServiceException("Seleccione por lo menos 1 cliente"));
			return processResult;
		}
		return processResult;
	}
}
